import Base64 from './base64.js'   // npm 也有，具体忘记名字了
import CryptoJS from './hmac-sha256.js'  //可以直接npm install CryptoJS

let keys4=Base64.encoder('xxxxxxxx')  // 秘钥

export default {
    jwt(payload, key =(Base64.decoder(keys4))) {
        if (this.isJSON(payload)) {
            if (typeof payload == 'object') {
                payload = JSON.stringify(payload)
            }
            let header = '{"typ":"JWT","alg":"HS256"}'
            let headerBase64 = Base64.encoder(header)
            let payloadBase64 = Base64.encoder(payload)
            let base64Token = headerBase64 + '.' + payloadBase64
            let signature = CryptoJS.HmacSHA256(base64Token, key)
            let signatureBase64 = Base64.hexToBase64(signature.toString())
            let jwt = base64Token + '.' + signatureBase64
            // console.log(jwt,'加密00000')
            return jwt;
        }else {
            throw '请传入正确的JSON字符串'
        }
    }, isJSON(str) {
        if (typeof str === 'string') {
            try {
                JSON.parse(str)
                return true
            } catch(e) {
                return false
            }
        }else if (typeof str === 'object') {
            try {
                return true
            } catch(e) {
                return false
            }
        }
    }
}

